#!/usr/bin/perl -w
use strict;
my $proclist='show full processlist';
my $innodb_tran_list = 'show innodb status \G';
my ($MYSQL_HOME,$DELIM,$HOST,$PORT,$USER,$PASS) = @ARGV;
my $PARAM="";
$PARAM="$PARAM -h\"$HOST\"" if (defined($HOST) && $HOST ne "");
$PARAM="$PARAM -P\"$PORT\"" if (defined($PORT) && $PORT ne "");
$PARAM="$PARAM -u\"$USER\"" if (defined($USER) && $USER ne "");
$PARAM="$PARAM -p\"$PASS\"" if (defined($PASS) && $PASS ne "");
my $MYSQL="$MYSQL_HOME/bin/mysql";
my $MYSQLADMIN="$MYSQL_HOME/bin/mysqladmin";
if ($^O =~ m/MSWin32/) {
  $MYSQL =~ s/\//\\/g;
  $MYSQLADMIN =~ s/\//\\/g;
}
# Check if mysqld is alive
my $retmsg=`$MYSQLADMIN $PARAM ping 2>&1`;
chomp($retmsg);
if ( "$retmsg" ne "mysqld is alive" ) {
    print "em_error=Status${DELIM}Down\n";
    exit 1;
}
my @proc=`$MYSQL -N -s $PARAM -e"$proclist"`;
foreach my $line(@proc) {
  chomp $line;
  my @row = split(/\t/,$line);
  my $id           = $row[0];
  my $user         = $row[1];
  my $host         = $row[2];
  my $db           = $row[3];
  my $command      = $row[4];
  my $lockwaittime = $row[5];
  my $state        = $row[6];
  my $stmt         = defined($row[7]) ? "$row[7]" : "NULL";
  my $host_ip      = "";
  if ( $state =~ /lock|flushing tables|waiting for table/ims) {
    #split host field to get host ip
    if ($host =~ /:/) {
       $host_ip = substr($host,0,index($host,":"));
    }
    else {
       $host_ip = $host;
    }
  my $user_host = join('@',$user,$host_ip);

  print "em_result=$id|$lockwaittime|$user_host|$state|$stmt\n";
  }
}

#MySQL thread id 367332, query id 435006445 dbatest.no.sohu.com 192.168.1.14 mysqlmon Updating
#update testib set name='test1' where id=1
#------- TRX HAS BEEN WAITING 18 SEC FOR THIS LOCK TO BE GRANTED:
my $InnodbLockWait = `$MYSQL -N -s $PARAM -e"$innodb_tran_list"`;
chomp $InnodbLockWait;
while  ( $InnodbLockWait =~ /(?:^MySQL thread id\s+(\d+),\s+query id\s+(\d+)\s+(\w+|\w+\.\w+\.\w+\.\w+)\s+(\d+|\d+\.\d+\.\d+\.\d+)?\s*(\w+)\s+([^\n]+)\n+([^\n]+)\n(?:^Trx read view.*?)?--+\s+TRX HAS BEEN WAITING\s+(\d+)\s+SEC FOR THIS LOCK TO BE GRANTED)+/msg) {
  #print "$&\n";
  my $id           = $1;
  my $user         = $5;
  my $host         = defined ($4) ? "$4" : "$3";;
  my $lockwaittime = $8;
  my $state        = $6;
  my $stmt         = $7;
  my $user_host    = join('@',$user,$host);
  print "em_result=$id|$lockwaittime|$user_host|$state|$stmt\n";
  #print "id: $1,query id:$2,host:$3,ip:$4,user:$5,state:$6,stmt:$7,waittime:$8\n";
}
